import type { AxiosResponse } from 'axios'

import { nextTick } from 'vue'
// import { useUserStore } from '../../../store/index';
import { store } from '@h5app/sheep/store'

import { useAuth, useRouter, useTips } from '@h5app/sheep/hooks'

enum ResponseErrorEnum {
  NotLogin = 10010,
  NotPermission = 50104,
}

export function useResponseInterceptor(config: AxiosResponse) {
  /**
   * 全局拦截请求发送后返回的数据，如果数据有报错则在这做全局的错误提示
   * 假设返回数据格式为：{ status: 1, error: '', data: '' }
   * 规则是当 status 为 1 时表示请求成功，为 0 时表示接口需要登录或者登录状态失效，需要重新登录
   * 请求出错时 error 会返回错误信息
   */

  if (!config?.data) {
    return Promise.reject(config)
  }
  const { code, success, msg, message, type } = config.data

  uni.hideLoading()

  if (
    !code &&
    [
      'application/octet-stream',
      'application/octet-stream;charset=utf-8',
      '.spreadsheetml.sheet',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    ].indexOf(type) > -1
  ) {
    return Promise.resolve(config)
  }
  if (!success) {
    useResponseInterceptorError({ message: msg || message, code })
    return Promise.reject(config.data)
  }
  return Promise.resolve(config.data)
  // useUserStore().logout();
}

export async function useResponseInterceptorError(error: any) {
  const router = useRouter()

  let message = error.message || '系统异常，请联系管理员'

  if (message === 'Network Error') {
    message = '后端网络故障'
  } else if (message?.includes?.('timeout')) {
    message = '接口请求超时'
  } else if (message?.includes?.('Request failed with status code')) {
    message = `接口${message.substr(message.length - 3)}异常`
  }

  uni.hideLoading()
  // uni.showToast({
  //   title: message,
  //   icon: 'none',
  // });

  switch (`${error.code}`) {
    case `${ResponseErrorEnum.NotLogin}`:
    case `${ResponseErrorEnum.NotPermission}`:
      const user = store.useUserStore()
      user.removeStorageSync()

      const auth = useAuth()
      // #ifdef H5
      // await auth.refreshLogin()
      router.push('login')

      // #endif
      try {
        break
      } catch {
        // router.push('login');
        return
      }

    default:
      uni.showToast({
        title: message,
        icon: 'none',
      })
      break
  }

  return Promise.reject(error)
}
